package com.platform.file.utils;

import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.http.Method;
import lombok.SneakyThrows;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class MinioTest {
    static MinioClient minioClient;
    static IMinioClient client;
    static{
        /*minioClient = MinioClient.builder().endpoint("http://172.18.13.101:9000").credentials("lFqKQb4hlaAIbLjy", "dLC5BZUwZXCsVReL8PL6wUd0KkW3Pea2")
                .build();*/
        minioClient = MinioClient.builder().endpoint("http://172.18.13.101:9000").credentials("lFqKQb4hlaAIbLjy", "dLC5BZUwZXCsVReL8PL6wUd0KkW3Pea2")
                .build();
        client = new IMinioClient(minioClient);
        client.setPublicBaseUrl("https://im.yzy-gx.com:13000/");//需要以‘/’结尾
        //minioClient.enableVirtualStyleEndpoint();
    }

    public static void main(String[] args) {
        String objectUrl=getPreviewFileUrl("chatfile","f7e31b2a-1ecf-491f-904e-c6444441fdbb/06411e60-9af5-11ee-873b-5daa422d84d2");
        //String objectUrl=getPresignedObjectPublicUrl("chatfile","f7e31b2a-1ecf-491f-904e-c6444441fdbb/06411e60-9af5-11ee-873b-5daa422d84d2",600,"https://im.yzy-gx.com:13000/");
        System.out.println("objectUrl = " + objectUrl);
    }



    /**
     * 获取指定桶中文件的临时url （配置中默认的公网地址）
     * @param bucket 桶
     * @param filename 文件名称
     * @param seconds 有效期 s
     */
    @SneakyThrows(Exception.class)
    public static String getPresignedObjectPublicUrl(String bucket, String filename, int seconds,String publicBaseUrl){
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(bucket)
                .object(filename)
                .expiry(seconds)
                .build();
        return client.getPresignedObjectUrl(build,publicBaseUrl);
    }

    /**
     * @method: getPreviewFileUrl
     * @description: 获取带时间的过期链接
     * @author: WuChang
     * @date: 2022/12/19 2:36 PM
     */
    public static String getPreviewFileUrl(String bucketName, String fileName) {
        GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .method(Method.GET)
                .expiry(30, TimeUnit.MINUTES)
                .build();
        String objectUrl = null;
        try {
            objectUrl = minioClient.getPresignedObjectUrl(build);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return objectUrl;
    }
}
